package com.letoken.platform.repo.app.redis;

import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @author： letokenlabs
 * @date： 2023/4/3
 * 登录后台黑名单
 */
@Slf4j
public class AdminLoginBlackListRedis {
    private StringRedisTemplate stringRedisTemplate;

    private AdminLoginBlackListRedis() {
        stringRedisTemplate = BeanUtil.getBean(StringRedisTemplate.class);
    }

    private enum Singleton {
        INSTANCE;
        private AdminLoginBlackListRedis instance;

        // JVM会保证此方法绝对只调用一次
        Singleton() {
            instance = new AdminLoginBlackListRedis();
        }
    }

    String adminLoginUsernameBlack = RedisKeyConstant.ADMIN_LOGIN_USERNAME_BLACK;

    public static AdminLoginBlackListRedis me() {
        return AdminLoginBlackListRedis.Singleton.INSTANCE.instance;
    }

    public boolean hasKey(String userName) {
        if (StringUtils.isNotBlank(userName)) {
            String key = adminLoginUsernameBlack + userName;
            String name = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(name)) {
                return true;
            }
        }
        return false;
    }

    public void setAdminUserName(String userName) {
        String key = adminLoginUsernameBlack + userName;
        if (StringUtils.isNotBlank(userName)) {
            String name = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isBlank(name)) {
                stringRedisTemplate.opsForValue().set(key, userName);
                stringRedisTemplate.expire(key, 1, TimeUnit.DAYS);
            }else {
                stringRedisTemplate.opsForValue().set(key, userName);
            }

        }
    }


}
